package com.ebuy.shopping.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ebuy.shopping.model.News;
import com.ebuy.shopping.service.INewsService;

@Controller
@RequestMapping("/news")
public class NewsController
{

    @Autowired
    private INewsService newsService;

    /*
     * 后台主页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index1()
    {
        return "manage/index";
    }

    /*
     * 到新闻列表页面
     */
    @RequestMapping("/news")
    public String notices(Model model) throws Exception
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", "create_time");
        map.put("sort", "asc");
        map.put("offset", 0);
        map.put("pageSize", 9);
        List<News> newss = newsService.getNewsPage(map);
        model.addAttribute("newss", newss);
        return "news/news";
    }

    // 到添加新闻页面

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add()
    {

        return "news/news-add";
    }

    // 执行添加

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Model model, News news) throws Exception
    {
        newsService.add(news);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", "create_time");
        map.put("sort", "asc");
        map.put("offset", 0);
        map.put("pageSize", 15);
        List<News> newss = newsService.getNewsPage(map);
        model.addAttribute("newss", newss);
        return "news/news";
    }

    // 到修改页面
    @RequestMapping("/update")
    public String update(int id, Model model) throws Exception
    {
        News news = newsService.load(id);
        model.addAttribute("news", news);
        return "news/news-update";
    }

    // 执行修改
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(News news) throws Exception
    {
        newsService.update(news);
        return "redirect:news";
    }

    // 执行删除
    @RequestMapping("/delete")
    public String delete(int id) throws Exception
    {
        newsService.delete(id);
        return "redirect:news";
    }

    // 到详情页面
    @RequestMapping("/detail")
    public String detail(int id, Model model) throws Exception
    {
        News news = newsService.load(id);
        model.addAttribute("news", news);
        return "news/newsDetails";
    }

}
